package top.zhangjianyong.tools.indicator.strategy.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.zhangjianyong.tools.indicator.context.IndicatorContext;
import top.zhangjianyong.tools.indicator.model.TechnicalIndicatorResult;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 技术指标比率指标计算器
 * 计算RSI/100、MACD/ATR等标准化比率特征
 *
 * @author zhangjianyong
 * @date 2024/01/01
 */
@Component
public class IndicatorRatioIndicator extends AbstractIndicator {

    private static final String INDICATOR_NAME = "INDICATOR_RATIO";

    @Autowired
    private RSIIndicator rsiIndicator;

    @Autowired
    private MACDIndicator macdIndicator;

    @Autowired
    private ATRIndicator atrIndicator;

    @Override
    public String getName() {
        return INDICATOR_NAME;
    }

    @Override
    public int getMinDataSize() {
        return 26; // 需要MACD和ATR的数据
    }

    @Override
    protected TechnicalIndicatorResult doCalculate(IndicatorContext context) {
        TechnicalIndicatorResult result = TechnicalIndicatorResult.success(getName());

        // 计算RSI/100
        TechnicalIndicatorResult rsiResult = rsiIndicator.calculate(context);
        if (rsiResult.isSuccess()) {
            BigDecimal rsi = rsiResult.getBigDecimalValue("rsi");
            if (rsi != null) {
                BigDecimal rsiRatio = rsi.divide(new BigDecimal(100), 4, RoundingMode.HALF_UP);
                result.addValue("rsi_ratio", rsiRatio);
            }
        }

        // 计算MACD/ATR
        TechnicalIndicatorResult macdResult = macdIndicator.calculate(context);
        TechnicalIndicatorResult atrResult = atrIndicator.calculate(context);

        if (macdResult.isSuccess() && atrResult.isSuccess()) {
            BigDecimal macd = macdResult.getBigDecimalValue("macd");
            BigDecimal atr = atrResult.getBigDecimalValue("atr");

            if (macd != null && atr != null && atr.compareTo(BigDecimal.ZERO) != 0) {
                BigDecimal macdAtrRatio = macd.divide(atr, 4, RoundingMode.HALF_UP);
                result.addValue("macd_atr_ratio", macdAtrRatio);
            }
        }

        // 计算MACD DIF/ATR
        if (macdResult.isSuccess() && atrResult.isSuccess()) {
            BigDecimal macdDif = macdResult.getBigDecimalValue("macd_dif");
            BigDecimal atr = atrResult.getBigDecimalValue("atr");

            if (macdDif != null && atr != null && atr.compareTo(BigDecimal.ZERO) != 0) {
                BigDecimal macdDifAtrRatio = macdDif.divide(atr, 4, RoundingMode.HALF_UP);
                result.addValue("macd_dif_atr_ratio", macdDifAtrRatio);
            }
        }

        return result;
    }
}

